/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, {
  memo,
  useState,
  useEffect,
  useCallback,
} from "react";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { View, Text } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import debounce from "lodash/debounce";
import { updateState } from "@/store/actions/global";
import {
  Icon,
  Empty,
  Cell,
  CellGroup,
  ActionSheet,
  Stepper,
  Field,
  Popup,
  Picker,
} from "@antmjs/vantui";
import Authorization from "@/components/Authorization";
import OptionTab from "@/components/OptionTab"
import Navbar from "@/components/Navbar"
import "./index.less";
import { themeColor } from "../../utils/config";

const Index = () => {
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, basket, basketUpdate, systemInfo } = globalData;
  const { screenHeight } = systemInfo;
  const dispatch = useDispatch();
  const optionData = [[
    {
      name: "新增清单",
    },
    {
      name: "编辑清单",
    },
    {
      name: "合并材料",
    },
    {
      name: "清空菜篮子",
      color: "#ee0a24",
    },
    {
      name: "取消",
      color: "#646566",
    },
  ], [
    {
      name: "取消合并材料",
    },
    {
      name: "清空菜篮子",
      color: "#ee0a24",
    },
    {
      name: "取消",
      color: "#646566",
    },
  ]];
  const [options, setOptions] = useState(optionData[0]);
  const [isMerge, setMerge] = useState(false);
  const [showOptionBar, setShowOptionBar] = useState(false);
  const [showEditTitlePop, setShowEditTitlePop] = useState(false);
  const [showEditMaterialPop, setShowEditMaterialPop] = useState(false);
  const [currentSelect, setCurrentSelect] = useState({});
  const [isEdit, setIsEdit] = useState(false);
  const [checkList, setCheckList] = useState([]);
  const [popValue, setPopValue] = useState({});
  const columnsData = ['适量', '毫升', '克', '勺', '个', '只', '片', '杯'];
  const [columns, setColumns] = useState(columnsData);
  const [showPicker, setShowPicker] = useState(false);
  const [canStep, setCanStep] = useState(true);
  const [mergeData, setMergeData] = useState([]);
  const updateBasket = () => {
    dispatch(
      updateState({
        basket,
      })
    );
    Taro.setStorageSync("basket", basket);
  }
  const setOpenState = (itemIndex) => {
    const item = basket[itemIndex];
    item.isOpen = !item.isOpen;
    updateBasket();
  };
  const onClickItem = (index) => {
    setOpenState(index);
  };
  const handleOptionBar = () => {
    setShowOptionBar(true)
  }
  const handleCheck = (index, material) => {
    console.log('check');
    let item = material[index];
    item.isCheck = !item.isCheck;
    material.splice(index, 1);
    if (item.isCheck) {
      material.push(item);
    } else {
      material.unshift(item);
    }
    updateBasket();
  };
  const handleCheck2 = (name,check) => {
    basket.forEach(item=>{
      item.material.forEach(data=>{
        if(data.material_name === name)
        data.isCheck = !check;
      })
    })
    updateBasket();
    calcuMerge();
    console.log(name,check);
  }
  const delMaterial = (material_index, material) => {
    let index = material.findIndex(item => item.material_index === material_index);
    material.splice(index, 1);
    updateBasket();
  };
  const handleClick = useCallback(
    debounce(
      (e, id) => {
        e.stopPropagation(); // 阻止事件冒泡
        if (!id) {
          console.log("not url");
          return;
        }
        let url = "/pages/recipeInfo/index?recipe_id=" + id;
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };
  const onClose = () => {
    setShowOptionBar(false);
  };
  const onPopClose = () => {
    setShowEditTitlePop(false);
    setShowEditMaterialPop(false);
    const { bindex, mindex } = currentSelect;
    if (bindex !== undefined && mindex === undefined) {
      basket[bindex].title = popValue.title;
      updateBasket();
    } else if (bindex !== undefined && mindex !== undefined && mindex !== -1) {
      console.log('edit-m', bindex, mindex, popValue);
      let m = basket[bindex].material;
      m[mindex] = popValue;
      updateBasket();
    }
    setTimeout(() => {
      setCurrentSelect({});
      setPopValue({});
    }, 300);
  }
  const handlePopDone = (type) => {
    const { bindex, mindex } = currentSelect;
    if (type === 'title') {
      if (popValue.title && bindex === undefined) {
        addNewList()
      }
    } else if (type === 'material') {
      if (mindex === -1) {
        console.log('add-m', bindex, mindex, popValue);
        let m = basket[bindex].material;
        m.unshift({
          ...popValue,
          isCheck: false,
          material_index: new Date().getTime(),
        });
        updateBasket();
      }
    }
    onPopClose();
  }
  const calcuMerge = () => {
    const arr = [];
    basket.forEach(item => {
      item.material.forEach(m => {
        let flag = arr.find(d => d.material_name === m.material_name);
        if (!flag) {
          arr.push({
            material_name: m.material_name,
            child: [{
              amount: m.material_amount,
              unit: m.material_unit,
            }],
            isCheck: m.isCheck
          })
        } else {
          if (!m.isCheck) {
            flag.isCheck = false;
          }
          let find = flag.child.find(d => d.unit === m.material_unit);
          if (find) {
            if (m.material_amount) {
              find.amount += m.material_amount;
            }
          } else {
            flag.child.push({
              amount: m.material_amount,
              unit: m.material_unit
            })
          }
        }
      })
    })
    console.log(arr);
    setMergeData(arr);
  }
  const onSelect = ({ detail }) => {
    console.log(detail);
    const { name } = detail;
    if (name === '清空菜篮子') {
      delItem(-1, 'all');
      setCheckList([]);
    } else if (name === '编辑清单') {
      setIsEdit(true);
    } else if (name === '新增清单') {
      if (basket.length > 9) {
        Taro.showModal({
          title: '提示',
          content: `菜篮子已经装不下啦`,
          showCancel: false,
        })
        return
      }
      setPopValue({ title: "" })
      setShowEditTitlePop(true);
    } else if (name === '合并材料') {
      calcuMerge();
      setMerge(true)
      setTimeout(() => {
        setOptions(optionData[1]);
      }, 500);
    } else if (name === '取消合并材料') {
      setMerge(false);
      setTimeout(() => {
        setOptions(optionData[0]);
      }, 500);
    }
  };
  const delItem = (id, type) => {
    if (type === 'all') {
      Taro.showModal({
        title: '提示',
        content: `你确定要删除所有清单吗`,
        success: function (res) {
          if (res.confirm) {
            Taro.setStorageSync("basket", []);
            dispatch(
              updateState({
                basket: [],
              })
            );
          }
        }
      })
    } else {
      Taro.showModal({
        title: '提示',
        content: `你确定要删除清单\r\n"${basket[id].title}"吗`,
        success: function (res) {
          if (res.confirm) {
            basket.splice(id, 1);
            updateBasket();
            setCheckList([]);
          }
        }
      })
    }
  }
  const handleEdit = (type) => {
    console.log(type);
    if (type === 'done') {
      setIsEdit(false)
    } else if (type === 'del') {
      console.log(checkList);
      if (checkList.length === 0) {
        return;
      }
      if (checkList.length === 1) {
        let index = basket.findIndex(item => item.timestamp === checkList[0]);
        delItem(index);
        return;
      }
      Taro.showModal({
        title: '提示',
        content: `你确定要删除选中的${checkList.length}个清单吗`,
        success: function (res) {
          if (res.confirm) {
            checkList.forEach(item => {
              let index = basket.findIndex(b => b.timestamp === item);
              if (index !== -1) {
                basket.splice(index, 1);
              }
            })
            setCheckList([]);
            updateBasket();
          }
        }
      })
    } else if (type === 'add') {
      if (basket.length > 9) {
        Taro.showModal({
          title: '提示',
          content: `菜篮子已经装不下啦`,
          showCancel: false,
        })
        return
      }
      setPopValue({ title: "" })
      setShowEditTitlePop(true)
    }
  }
  const addNewList = () => {
    let obj = {
      timestamp: new Date().getTime(),
      isOpen: true,
      title: popValue.title,
      material: [
      ]
    }
    basket.unshift(obj)
    updateBasket();
    setIsEdit(true)
    Taro.pageScrollTo({
      scrollTop: 0,
      duration: 500
    })
  }
  const findCheck = (timestamp) => {
    let flag = checkList.find(item => item === timestamp)
    return flag !== undefined
  }
  const checkEdit = (e, type, timestamp) => {
    e.stopPropagation(); // 阻止事件冒泡
    if (type === 'all') {
      let list = [];
      if (checkList.length < basket.length) {
        basket.forEach(item => {
          list.push(item.timestamp);
        })
      }
      setCheckList(list)
    } else {
      let index = checkList.findIndex(item => item === timestamp);
      if (index !== -1) {
        setCheckList(pre => {
          pre.splice(index, 1)
          return [...pre]
        })
      } else {
        setCheckList(pre => {
          pre.push(timestamp);
          return [...pre]
        })
      }
    }

  }
  const isCheckAll = () => {
    let flag = true;
    if (!basket.length) {
      return false
    }
    for (const { timestamp } of basket) {
      let find = checkList.find((item) => {
        return item === timestamp
      })
      if (find === undefined) {
        flag = false;
        break;
      }
    }
    return flag
  }
  const getPickerData = (index) => {
    const { material } = basket[index];
    let arr = []
    material.forEach(item => {
      if (item.material_amount && item.material_unit !== '') {
        arr.push(item.material_unit);
      }
    })
    arr = Array.from(new Set([...arr, ...columnsData,]));
    console.log(arr);
    setColumns(arr);
  }
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
  }, [isLogin, dispatch]);
  useDidShow(() => {
    if (basketUpdate) {
      basket[0].isOpen = true;
      Taro.setStorageSync('basketUpdate', false);
      dispatch(updateState({
        basketUpdate: false,
      }))
    }
    calcuMerge()
  })
  return (
    <View className='basket'>
      <Navbar title='菜篮子' arrow='true'></Navbar>
      <Authorization canClose={false}></Authorization>

      <View>{!isEdit ? <OptionTab onClick={handleOptionBar} top={.75 * screenHeight} /> : null}</View>

      <View className='optionBar'>
        <ActionSheet
          show={showOptionBar}
          actions={options}
          onClose={onClose}
          onSelect={onSelect}
        />
      </View>
      <View className='editMaterialPop'>
        <Popup
          className='my-pop'
          show={showEditMaterialPop}
          round
          position='bottom'
          style='min-height: 60%'
          onClose={onPopClose}
        >
          <View className='pop-title'>
            <Text className='title'>{currentSelect.mindex === -1 ? '新增材料' : '编辑材料'}</Text>
            <Text className='done' onClick={() => handlePopDone('material')}>完成</Text>
          </View>
          <View className='main'>
            <View className='cell'>
              <View className='lable'>材料名</View>
              <View className='field'>
                <Field
                  value={popValue.material_name}
                  clearable
                  placeholder='材料'
                  maxlength='30'
                  onChange={
                    ({ detail }) => {
                      setPopValue((pre) => {
                        return {
                          ...pre,
                          material_name: detail
                        }
                      })
                    }
                  }
                />
              </View>
            </View>
            <View className='cell'>
              <View className='lable'>数量|单位</View>
              {popValue.material_amount > 0 &&
                <Stepper
                  value={popValue.material_amount}
                  step={0.5}
                  max={999}
                  min={0}
                  asyncChange
                  onBlur={({ value }) => {
                    let num = Number(value);
                    num = parseFloat(num.toFixed(1));
                    if (num === 0) {
                      num = null;
                    }
                    setCanStep(true);
                    setPopValue(pre => {
                      return {
                        ...pre,
                        material_amount: num
                      }
                    })
                  }}
                  onFocus={() => {
                    setCanStep(false);
                  }}
                  onMinus={() => {
                    if (!canStep) {
                      return
                    }
                    setPopValue(pre => {
                      let num = pre.material_amount - 0.5;
                      if (num <= 0) {
                        num = null;
                      }
                      return {
                        ...pre,
                        material_amount: num
                      }
                    })
                  }}
                  onPlus={() => {
                    if (!canStep) {
                      return
                    }
                    setPopValue(pre => {
                      return {
                        ...pre,
                        material_amount: pre.material_amount += 0.5
                      }
                    })
                  }}
                />}
              <View className={`'field' ${showPicker ? 'open-class' : ''}`}>
                <Field
                  value={popValue.material_unit}
                  placeholder='单位'
                  icon='arrow-down'
                  onClickIcon={() => {
                    setShowPicker((pre) => !pre);
                  }}
                  maxlength='15'
                  onChange={
                    ({ detail }) => {
                      setPopValue((pre) => {
                        return {
                          ...pre,
                          material_unit: detail
                        }
                      })
                    }
                  }
                />
              </View>
            </View>
            <View className='picker'>
              {showPicker && <Picker
                columns={columns}
                defaultIndex={0}
                visibleItemCount={5}
                itemHeight={40}
                onChange={({ detail }) => {
                  setPopValue((pre) => {
                    let { material_amount } = pre;
                    if (detail.value === '适量') {
                      material_amount = null
                    } else if (material_amount === null || material_amount <= 0) {
                      material_amount = 1;
                    }
                    return {
                      ...pre,
                      material_amount,
                      material_unit: detail.value
                    }
                  })
                }}

              ></Picker>
              }
            </View>
          </View>
        </Popup>
      </View>
      <View className='editTitlePop'>
        <Popup
          className='my-pop'
          show={showEditTitlePop}
          round
          position='bottom'
          style='min-height: 60%'
          onClose={onPopClose}
        >
          <View className='pop-title'>
            <Text className='title'>{currentSelect.bindex !== undefined ? '编辑清单' : '新建清单'}</Text>
            <Text className='done' onClick={() => handlePopDone('title')}>完成</Text>
          </View>
          <View className='main'>
            <View className='cell'>
              <View className='lable'>清单名</View>
              <View className='field'>
                <Field
                  value={popValue.title}
                  clearable
                  placeholder='请输入清单名称'
                  maxlength='50'
                  onChange={
                    ({ detail }) => {
                      setPopValue({
                        title: detail
                      })
                    }
                  }
                />
              </View>
            </View>
          </View>
        </Popup>
      </View>
      {!basket.length ? (
        <Empty description='菜篮子空空如也~' />
      ) : !isMerge ? (
        <View className='list'>
          {basket.map((bitem, bindex) => {
            const { material, isOpen, timestamp } = bitem;
            let checkNum = 0;
            material.forEach((bitem) => {
              if (bitem.isCheck) {
                checkNum++;
              }
            });
            return (
              <View
                className='item'
                key={timestamp}
              >
                <CellGroup className={`my-cell ${isOpen ? 'open-class' : ''}`}>
                  <Cell
                    onClick={() => { onClickItem(bindex) }}
                    onLongPress={() => {
                      setCurrentSelect({ bindex });
                      setPopValue({ title: basket[bindex].title });
                      setShowEditTitlePop(true);
                    }}
                    isLink
                    size='large'
                    arrowDirection='down'
                    renderTitle={<View className='title'><Text>{bitem.title}</Text></View>}
                    value={(checkNum + "/" + material.length)}
                    renderIcon={
                      isEdit ?
                        <Icon size='50' name={findCheck(timestamp) ? 'checked' : 'circle'} color={findCheck(timestamp) ? themeColor : '#c8c9cc'} className='des'
                          onClick={(e) => checkEdit(e, 'single', timestamp)}
                        ></Icon>
                        :
                        bitem.recipe_id ? (
                          <Icon
                            name='description'
                            className='des'
                            color='#333333'
                            size='35'
                            onClick={(e) => {
                              handleClick(e, bitem.recipe_id);
                            }}
                          />
                        ) : null
                    }
                  />
                </CellGroup>
                {isOpen ?
                  <CellGroup className='material-list'>
                    {isEdit &&
                      <Cell
                        className='material'
                        renderTitle={
                          <View className='title'>
                            <View className='radio'                              >
                              <Icon size='50' name='add' color='#ed5814'
                                onClick={() => {
                                  setCurrentSelect({ bindex, mindex: -1 });
                                  setPopValue({
                                    material_amount: 1,
                                  });
                                  getPickerData(bindex);
                                  setShowEditMaterialPop(true);
                                }}
                              ></Icon>
                            </View>
                          </View>
                        }

                      />
                    }
                    {material.map((item, index) => {
                      const {
                        material_index,
                        material_name,
                        material_amount,
                        material_unit,
                        isCheck,
                      } = item;
                      return (
                        <Cell
                          key={material_index}
                          className={`material`}
                          renderTitle={<View className='title'>
                            {isEdit ? <View className='radio' onClick={(e) => {
                              delMaterial(material_index, material)
                            }}
                            >
                              <Icon size='50' name='close' color='#ee0a24'></Icon>
                            </View> : <View className='radio' onClick={(e) => {
                              handleCheck(index, material)
                            }}
                            >
                                <Icon size='50' name={isCheck ? 'checked' : 'circle'} color={isCheck ? themeColor : '#c8c9cc'} ></Icon>
                              </View>}
                          </View>}
                          renderRightIcon={
                            <>
                              <View className='name'
                                onClick={() => {
                                  setCurrentSelect({ bindex, mindex: index });
                                  setPopValue({
                                    material_name: basket[bindex].material[index].material_name,
                                    material_amount: basket[bindex].material[index].material_amount,
                                    material_unit: basket[bindex].material[index].material_unit,
                                  });
                                  setShowEditMaterialPop(true);
                                  getPickerData(bindex);
                                }}
                              >
                                <Text className={isCheck ? "done" : ""} >
                                  {material_name}
                                </Text>
                              </View>
                              <View className={`amount ${isCheck ? "done" : ""}`}
                                onClick={() => {
                                  setCurrentSelect({ bindex, mindex: index });
                                  setPopValue({
                                    material_name: basket[bindex].material[index].material_name,
                                    material_amount: basket[bindex].material[index].material_amount,
                                    material_unit: basket[bindex].material[index].material_unit,
                                  });
                                  setShowEditMaterialPop(true);
                                  getPickerData(bindex);
                                }}
                              >
                                <Text>{material_amount}{material_unit}</Text>
                              </View>
                            </>
                          }
                        />
                      );
                    })}
                  </CellGroup>
                  : null}
              </View>
            );
          })}
        </View>
      ) : <View className='list'>
            <CellGroup className='material-list'>
              {mergeData.map((item, index) => {
                const { material_name, child, isCheck } = item;
                let amount_unit = '';
                child.forEach((item,index)=>{
                  amount_unit += `${item.amount||""}${item.unit||""}`;
                  if(index !== child.length-1){
                    amount_unit+=" + "
                  }
                })
                return (
                  <Cell
                    key={material_name}
                    className={`material`}
                    renderTitle={<View className='title'>
                      <View className='radio' onClick={(e) => {
                        handleCheck2(material_name,isCheck)
                      }}
                      >
                        <Icon size='50' name={isCheck ? 'checked' : 'circle'} color={isCheck ? themeColor : '#c8c9cc'} ></Icon>
                      </View>
                    </View>}
                    renderRightIcon={
                      <>
                        <View className='name'
                        >
                          <Text className={isCheck ? "done" : ""} >
                            {material_name}
                          </Text>
                        </View>
                        <View className={`amount ${isCheck ? "done" : ""}`}
                        >
                          <Text>{amount_unit}</Text>
                        </View>
                      </>
                    }
                  />
                );
              })}
            </CellGroup>
          </View>}
      <View>
        {isEdit ?
          <View className='edit-nav'>
            <View className='block'></View>
            <View className='area-block'></View>
            <View className='main'>
              <View className='container'> <Icon size='50' name={isCheckAll() ? 'checked' : 'circle'} color={isCheckAll() ? themeColor : '#c8c9cc'} onClick={(e) => checkEdit(e, 'all')}></Icon>
                <View className='btn-group'>
                  <View className='btn-del' onClick={() => { handleEdit('del') }} style={{
                    borderColor: checkList.length ? 'rgba(238, 10, 36, 1)' : 'rgba(238, 10, 36, .6)',
                    backgroundColor: checkList.length ? 'rgba(238, 10, 36, 1)' : 'rgba(238, 10, 36, .6)'
                  }}
                  >删除</View>
                  <View className='btn-add' onClick={() => { handleEdit('add') }}>新增</View>
                  <View className='btn-done' onClick={() => { handleEdit('done') }}>完成</View>
                </View>
              </View>
              <View className='area-block'></View>
            </View>
          </View>
          : null}
      </View>
    </View >
  );
};

export default memo(Index);
